// SPDX-License-Identifier: Apache-2.0

package chisel3

import chisel3.internal._
import scala.language.experimental.macros

object withClockAndReset {

  def apply[T](clock: Clock, reset: Reset)(block: => T): T = apply(Some(clock), Some(reset))(block)

  def apply[T](clock: Option[Clock], reset: Option[Reset])(block: => T): T = {
    val parentClock = Builder.currentClock
    val parentReset = Builder.currentReset

    Builder.currentClock = clock
    Builder.currentReset = reset

    val res = block // execute block

    Builder.currentClock = parentClock
    Builder.currentReset = parentReset
    res
  }
}

object withClock {

  def apply[T](clock: Clock)(block: => T): T = apply(Some(clock))(block)

  def apply[T](clock: Option[Clock])(block: => T): T = {
    val parentClock = Builder.currentClock
    Builder.currentClock = clock
    val res = block // execute block
    Builder.currentClock = parentClock
    res
  }
}

object withReset {

  def apply[T](reset: Reset)(block: => T): T = apply(Some(reset))(block)

  def apply[T](reset: Option[Reset])(block: => T): T = {
    val parentReset = Builder.currentReset
    Builder.currentReset = reset
    val res = block // execute block
    Builder.currentReset = parentReset
    res
  }

}

object withoutIO {

  def apply[T](block: => T)(implicit si: experimental.SourceInfo): T = {
    Builder.currentModule.get.disallowIO(block)
  }
}
